﻿using System.Linq;
using System.Windows;
using PdfRotator.Properties;
using PdfRotator.Util;
using PdfRotator.ViewModel;

namespace PdfRotator
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private readonly MainViewModel _mainViewModel = PdfRotator.MainWindow.MainViewModel;
        private bool _commandline = true;

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            _commandline = e.Args.Length > 0;

            if (!_commandline)
            {
                _mainViewModel.OddPageRotation = EnumUtil.Parse<PdfRotation>(Settings.Default.OddPageRotation);
                _mainViewModel.EvenPageRotation = EnumUtil.Parse<PdfRotation>(Settings.Default.EvenPageRotation);
                return;
            }

            var options = new Options();
            if (!CommandLine.Parser.Default.ParseArguments(e.Args, options))
            {
                MessageBox.Show(options.GetUsage());
                Shutdown(CommandLine.Parser.DefaultExitCodeFail);
                return;
            }

            var oddPageRotation = GetRotation(options.OddPageRotation ?? "");
            var evenPageRotation = GetRotation(options.EvenPageRotation ?? "");
            foreach (var path in options.Files.Where(PdfUtil.IsValidPdfFile))
            {
                PdfUtil.Rotate(path, oddPageRotation, evenPageRotation);
            }
            Shutdown();
        }

        private void App_Exit(object sender, ExitEventArgs e)
        {
            if (!_commandline)
            {
                Settings.Default.OddPageRotation = _mainViewModel.OddPageRotation.ToString();
                Settings.Default.EvenPageRotation = _mainViewModel.EvenPageRotation.ToString();
                Settings.Default.Save();
            }
        }

        private static PdfRotation GetRotation(string rotation)
        {
            switch (rotation.ToLower())
            {
                case "90":
                    return PdfRotation.Rotate90;
                case "180":
                    return PdfRotation.Rotate180;
                case "270":
                    return PdfRotation.Rotate270;
                case "reset":
                    return PdfRotation.SetRotate0;
            }
            return PdfRotation.Rotate0;
        }
    }
}
